const validate = require("../middleware/validate");
const ResponseMessage = require("../response/message");

const log4js = require("log4js");
const logger = log4js.getLogger();

const { query,body } = require("express-validator");

function checkQueryExists(req,res,msgs = ["缺失查询字符串参数","缺少 query 查询字符串参数"]){
    if(!req.query){
        logger.warn(req.ip + " - " + req.method + " - " + req.originalUrl + " - "+msgs[0])
        res.send(new ResponseMessage(400, msgs[1], {}));
     }
}

exports.getSubjectInfosParamsValidator = (req,res,next) => {
    checkQueryExists(req,res);
    (async (callback) => {
       validate([
        //    query("searchType").optional().exists({checkFalsy:true}).withMessage("搜索类型字段不存在").notEmpty().withMessage("搜索类型不能为空"),
           query("searchContent").optional().notEmpty().withMessage("搜索的内容不能为空"),
           query("pageIndex").optional().notEmpty().withMessage("当前页不能为空").bail().custom(callback("页码必须是数字")),
           query("pageSize").optional().notEmpty().withMessage("页大小不能为空").bail().custom(callback("页大小必须是数字"))
      ])(req,res,next)
    })((msg) => {
        return async (value)=>{
           if(!/\d/.test(value)){
               return Promise.reject(msg);
           }
        }
    })
}

exports.addSubjectParamsValidator = async (req,res,next) => {
    if(!req.body){
        logger.warn(req.ip + " - " + req.method + " - " + req.originalUrl + " - 缺少请求体")
        res.send(new ResponseMessage(400, "缺少请求体", {}));
    }
    validate([
        body("subjectNo").notEmpty().withMessage("科目编号不能为空"),
        body("subjectName").notEmpty().withMessage("科目名称不能为空"),
        // body("gradeIds").notEmpty().withMessage("班级ID不能为空"),
        // body("departmentIds").notEmpty().withMessage("学院ID不能为空"),
    ])(req,res,next)
}

exports.deleteSubjectParamsValidator = async (req,res,next) => {
    checkQueryExists(req,res);
    validate([
        query("id").notEmpty().withMessage("ID 不能为空")
    ])(req,res,next);
}

exports.updateTeacherParamsValidator = async (req,res,next) => {
    if(!req.body){
        logger.warn(req.ip + " - " + req.method + " - " + req.originalUrl + " - 缺少请求体")
        res.send(new ResponseMessage(400, "缺少请求体", {}));
    }
    validate([
        body("_id").notEmpty().withMessage("id 不能为空"),
        body("subjectNo").optional().notEmpty().withMessage("科目编号不能为空"),
        body("subjectName").optional().notEmpty().withMessage("科目名称不能为空"),
        // body("gradeIds").optional().notEmpty().withMessage("班级ID不能为空"),
        // body("departmentIds").optional().notEmpty().withMessage("学院ID不能为空"),
        ])(req,res,next)
}